package com.hiray.restcache

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.GsonBuilder
import com.hiray.restcache.api.RestApi
import com.hiray.restcache.api.RestApiHelper
import com.zmy.rxcache.RxCache
import es.dmoral.toasty.Toasty
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_text.*

class TextActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_text)

        supportActionBar?.title = "首页"

    }


    @SuppressLint("SetTextI18n")
    override fun onResume() {
        super.onResume()
        val subscribe = RxCache.Builder()
            .setCacheDir(cacheDir)
            .build()
            .create(RestApiHelper.create(), RestApi::class.java)
            .getIndex()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({

                response_text.text = "${if (it.isCache) "缓存数据" else "网络数据"}\n" +
                        GsonBuilder().setPrettyPrinting()
                            .create().toJson(it.data)

            }, {

                Toasty.info(
                    this,
                    it.message ?: ""
                ).show()
            }, {

            })
    }

    fun promotion(view: View) {
        startActivity(Intent(this, IndexPromotionActivity::class.java))
    }
}